package com.mc.web;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.mc.model.AProperty;
import com.mc.model.Article;
import com.mc.model.ArticleProperty;
import com.mc.model.ArticlePropertyList;
import com.mc.model.Menu;
import com.mc.model.Paging;
import com.mc.model.Path;
import com.mc.model.SubMenu;
import com.mc.model.User;
import com.mc.service.APropertyService;
import com.mc.service.ArticlePropertyService;
import com.mc.service.ArticleService;
import com.mc.service.MenuService;
import com.mc.service.SubMenuService;
import com.mc.utils.PathUtil;

/**
 * 后台对文章的管理
 * :包括文章的添加、删除、修改以及对文章属性的添加、删除、修改
 */
@Controller
@RequestMapping("/backend/article")
@SessionAttributes("user")
public class ArticleAction {
	
	@Autowired private ArticleService articleService;					//文章持久层管理
	@Autowired private APropertyService aPropertyService;				//文章属性数据管理
	@Autowired private ArticlePropertyService articlePropertyService;	//文章与属性对应中间数据管理
	//菜单相关持久层
	@Autowired private MenuService menuService;
	@Autowired private SubMenuService subMenuService;
	/*-------------------文章管理START----------------------*/
	/**添加文章界面*/
	@RequestMapping("/addui")
	public String addArticleUI(ModelMap modelMap) {
		
		//查询所有属性,并存入modelMap，以传入视图
		List<AProperty> propertyList = aPropertyService.selectAll();
		
		modelMap.addAttribute("propertyList", propertyList);
		modelMap.addAttribute("menus", getMenus());	//将菜单注入modelMap
		
		Path path = PathUtil.setPathParams(new String[]{"PackageName:backend","ViewName:addarticle","ViewTitle:添加文章","smenu:article","mmenu:addarticle"});				
		return PathUtil.returnStr(path, modelMap);
	}
	
	/**添加文章的实现*/
	@RequestMapping("/add")
	public String addArticle(ModelMap modelMap, Article article, ArticlePropertyList articlePropertyList, HttpSession session) {
		if (article != null && article.getTitle() != null && article.getContent() != null
				&& !article.getTitle().trim().equals("") && !article.getContent().trim().equals("")) {
			List<ArticleProperty> apList = articlePropertyList.getAp();
			cleanArticlePropertyList(apList);
			
			//----------所属栏目预留区
			
			article.setFlag((short) apList.size());		//将属性的数量赋值给文章的标志列，便于在以后查询中判断是否在属性表中查找元素
			article.setAuthor(((User) session.getAttribute("user")).getId());	//将当前登录用户id存入article对象
			int row = articleService.insertSelective(article);	//将文章插入数据库，并返回自动生成的主键存入article对象中
			
			if (row > 0) {
				//插入属性
				for (ArticleProperty ap : apList) {
					if (ap.getPropertyId() != null) {
						ap.setArticleId(article.getId());	//将文章主键赋值给属性对应的article_id上
						articlePropertyService.insertSelective(ap);
					}
				}
				
				modelMap.addAttribute("message", true);
			} else {
				modelMap.addAttribute("message", false);
			}

		}

		return "forward:/backend/article/addui";
	}
	
	/**修改视图*/
	@RequestMapping("/update/{id}")
	public String updateUI(ModelMap modelMap, @PathVariable Integer id) {
		Article article = articleService.selectByPrimaryKeyAndCascade(id);
		
		modelMap.addAttribute("article", article);
		//查询所有属性,并存入modelMap，以传入视图
		List<AProperty> propertyList = aPropertyService.selectAll();
		modelMap.addAttribute("propertyList", propertyList);
		modelMap.addAttribute("menus", getMenus());	//将菜单注入modelMap
		
		Path path = PathUtil.setPathParams(new String[]{"PackageName:backend","ViewName:articleupdate","ViewTitle:修改文章","smenu:article","mmenu:mgarticle"});				
		return PathUtil.returnStr(path, modelMap);
	}
	
	/**修改*/
	@RequestMapping("/update")
	public String update(ModelMap modelMap, Article article, ArticlePropertyList articlePropertyList) {
		if (article.getId() == null)
			return "forward:/backend/article/manager";
		
		if (article != null && article.getTitle() != null && article.getContent() != null
				&& !article.getTitle().trim().equals("") && !article.getContent().trim().equals("")) {
			
			int row = articleService.updateByPrimaryKeySelective(article);
			if (row > 0) {
				//修改属性[先删除该文章的所有属性，在将页面上的属性添加回来，便可去除属性的等式判断与修改]
				//从页面表单接收到的属性集合
				List<ArticleProperty> apList = articlePropertyList.getAp();
				cleanArticlePropertyList(apList);
				//找到与此文件相关的属性
				List<ArticleProperty> articleProperty = articlePropertyService.selectByArticleID(article.getId());
				//删除属性
				for (ArticleProperty oldAp : articleProperty) {
					if (oldAp.getId() != null) {
						articlePropertyService.deleteByPrimaryKey(oldAp.getId());
					}
				}
				
				//添加属性
				for (ArticleProperty ap : apList) {
					if (ap.getPropertyId() != null) {
		System.out.println("------" + ap.getPropertyId() + "-===" + ap.getPropertyVale());
						ap.setArticleId(article.getId());	//将文章主键赋值给属性对应的article_id上
						articlePropertyService.insertSelective(ap);
					}
				}
				
				modelMap.addAttribute("message", true);
			} else {
				
				modelMap.addAttribute("message", false);
			}
		
		}
		return "forward:/backend/article/update/" + article.getId();
	}
	
	/**文章管理界面*/
	@RequestMapping("/manager")
	public String managerUI(ModelMap modelMap, @RequestParam(required=false) Integer p) {
		Path path = PathUtil.setPathParams(new String[]{"PackageName:backend","ViewName:articlemanage","ViewTitle:文章管理","smenu:article","mmenu:mgarticle"});				
		return PathUtil.returnStr(path, modelMap);
	}
	
	/**文章详情*/
	@RequestMapping("/detail/{id}")
	public String managerUI(ModelMap modelMap, @PathVariable int id) {
		Article article = articleService.selectByPrimaryKey(id);
		
		modelMap.addAttribute("article", article);
		
		Path path = PathUtil.setPathParams(new String[]{"PackageName:backend","ViewName:articledetail","ViewTitle:文章详情","smenu:article","mmenu:mgarticle"});				
		return PathUtil.returnStr(path, modelMap);
	}
	
	
	/**文章列表*/
	@RequestMapping("/list")
	public String list(ModelMap modelMap, @RequestParam(required=false) Integer p) {
		Paging<Article> paging = new Paging<Article>();
		paging.setPageIndex(p);
		paging.setSize(9);
		List<Article> acticleList = articleService.selectLimit(paging.getStartIndex() , paging.getSize());
		
		//将菜单名设置进文章属性中，
		for (Article ar : acticleList) {
			SubMenu sm = subMenuService.selectByPrimaryKey(ar.getMenuId());
			if (sm != null)
				ar.setMenuName(sm.getParentMenu().getName() + "--" + sm.getName());
		}
		
		paging.setDateCount(articleService.count());	//设置数据总量
		paging.setDates(acticleList);
		modelMap.addAttribute("acticleList", acticleList);
		modelMap.addAttribute("paging", paging);	//将分页信息闯入modelMap
		
		//Path path = PathUtil.setPathParams(new String[]{"PackageName:backend","ViewName:articlelist","ViewTitle:文章列表","smenu:department","mmenu:mgdepartment"});				
		//return PathUtil.returnStr(path, modelMap);
		return "backend.articlelist";
	}

	/**删除文章*/
	@RequestMapping("/del")
	public String del(ModelMap modelMap, @RequestParam Integer articleId) {
		//找到与此文件相关的属性
		List<ArticleProperty> articleProperty = articlePropertyService.selectByArticleID(articleId);
		//删除属性
		for (ArticleProperty oldAp : articleProperty) {
			if (oldAp.getId() != null) {
				articlePropertyService.deleteByPrimaryKey(oldAp.getId());
			}
		}
		
		int row = articleService.deleteByPrimaryKey(articleId);
		if (row > 0) {
			modelMap.addAttribute("delSuccess", true);
		} else 
			modelMap.addAttribute("delSuccess", false);
		
		return "forward:/backend/article/list";
	}
	
	@RequestMapping("/propertymanage")
	/**属性管理*/
	public String propertyManage(ModelMap modelMap) {
		List<AProperty> aps = aPropertyService.selectAll();
		
		modelMap.addAttribute("propertys", aps);
		
		Path path = PathUtil.setPathParams(new String[]{"PackageName:backend","ViewName:articlepropertymanage","ViewTitle:属性管理","smenu:article","mmenu:mgarticleProperty"});				
		return PathUtil.returnStr(path, modelMap);
	}
	
	@RequestMapping("/delproperty")
	@ResponseBody
	/**删除属性*/
	public String delProperty(@RequestParam(value="id",required=true) int id) {
		//这里并不是真的删除数据，而是将属性的valid的值设为false
		AProperty ap = new AProperty();
		ap.setId(id);
		ap.setValid((short) 0);
		int row = aPropertyService.updateValidByPrimaryKey(ap);
		
		if (row > 0)
			return "success";
		else 
			return "failed";
	}
	
	@RequestMapping("/addpro")
	@ResponseBody
	/**设置属性为有效*/
	public String setPropertyToValid(@RequestParam(value="id",required=true) int id) {
		AProperty ap = new AProperty();
		ap.setId(id);
		ap.setValid((short) 1);
		int row = aPropertyService.updateValidByPrimaryKey(ap);
		
		if (row > 0)
			return "success";
		else 
			return "failed";
	}
	
	/**删除属性*/
	@RequestMapping("/addnewproperty")
	@ResponseBody
	public String addNewProperty(AProperty pro) {
		if (pro.getName() != null && !pro.getName().trim().equals("")) {
			int row = aPropertyService.insertSelective(pro);
			
			if (row > 0)
				return "{'status':'success', 'id':'"+pro.getId()+"'}";
		}
		
		return "{status:failed}";
	}
	
	/*-------------------文章管理END----------------------*/
	/**清理不合法的属性项*/
	private void cleanArticlePropertyList(List<ArticleProperty> apList) {
		List<ArticleProperty> delList = new ArrayList<ArticleProperty>();
		if (apList != null) {
			for (ArticleProperty ap : apList) {
				if (ap.getPropertyId() == null || ap.getPropertyId() < 1 || ap.getPropertyVale().equals("")) {
					delList.add(ap);
				}
			}
			
			for (ArticleProperty ap : delList) {
				apList.remove(ap);
			}
			
		}
	}
	
	//获取所有菜单项
	private List<Menu> getMenus() {
		List<Menu> menus = menuService.selectAllMenu();
		
		for (Menu menu : menus) {
			List<SubMenu> subMenus = subMenuService.selectSubMenuByMid(menu.getId());
			menu.setChilds(subMenus);
		}
		
		return menus;
	}
}
